<?php
class User{
	public $picPath='images/users/';
	public $path='../blogdata/';
	function __construct(){
		date_default_timezone_set('PRC');
	}
/*创建新用户*/
	function createUser($username,$password,$authority=2,$headPic='NaN'){
		$pattern='/\W/';
		$flag=$username.$password;
		if(preg_match($pattern,$flag))
			return false;
		$sql='insert into user values(null,"'.$username.'","'.md5($password).'","'.$username.'",'.$authority.',"'.$headPic.'")';
		if($this->runMysql($sql))
			return true;
		else
			return false;
	}
	function userList(){
		$result=$this->runMysql('select id,user,authority,head_picture from user order by id');
		return $result;
	}
/*获取用户头像*/
	function getHeadPic($uid){
		$result=$this->runMysql('select head_picture from user where id='.$uid);
		if($result)
			return $result[0]['head_picture'];
	}
/*更改权限*/
	function changeAuthority($id,$authority){
		$sql='update user set authority='.$authority.' where id='.$id;
		$this->runMysql($sql);
		$result=$this->runMysql('select authority from user where id='.$id);
		if($result[0]['authority']==$authority)
			return true;
		else
			return false;
		
	}
/*删除用户*/	
	function destroyUser($uid){
		if(!is_numeric($uid))
			return false;
		//删除账户、文章、文章相关评论
		$sql=array();
		include 'connect.inc.php';
			/* delete files */
		$picName=$this->getHeadPic($uid);
		$headPic=$this->picPath.$picName;
		$this->deleteFile($headPic);
		$path=$this->path.$uid;
		$file=$this->deleteFile($path);
			/* delete comments */
		$sql_search_blog='select id from blog where user_id='.$uid;
		$result=$mysqli->query($sql_search_blog);
		for($i=0;$row=$result->fetch_assoc();$i++){
			$aid=$row['id'];
			$sql[$i]='delete from comments where user_id='.$uid.' or blog_id='.$aid;
		}
		$sql_comm=implode(';',$sql);
		if($sql_comm)
			$comm=$mysqli->multi_query($sql_comm);
		else
			$comm=true;
			/* delete blog */	
		$sql_blog='delete from blog where user_id='.$uid;
		$blog=$mysqli->query($sql_blog);
			/* delete user */
		$sql_user='delete from user where id='.$uid;
		$user=$mysqli->query($sql_user);
		if($file&&$comm&&$blog&&$user)
			return true;
		else 
			return false;
 	}
	private function runMysql($sql){
		include 'connect.inc.php';
		$result=$mysqli->query($sql);
		if($mysqli->error)
			return $mysqli->error;
		if(is_object($result)){			//插入或者是错误时，返回bool值
			$output=array();			//插入时，不赋值给变量
			for($i=0;$row=$result->fetch_assoc();$i++){
				$output[$i]=$row;
			}
			return $output;				//返回一个二维数组
		}else
			return true;
		$mysqli->close();
	}
//删除用户目录
	private function deleteFile($path){
		if(!file_exists($path))
			return true;
		if(is_file($path)){
			unlink($path);
			return true;
		}else{
			$dirHandle=opendir($path);
			while($dirName=readdir($dirHandle)){
				if($dirName!='.'&&$dirName!='..'){
					$dir=$path.'/'.$dirName;
					$this->deleteFile($dir);
				}
			}
			rmdir($path);
		}
	}

}
